# /asterisk

Analyze an Asterisk PBX call log and generate a professional expert conclusion.

## Usage

Paste the full Asterisk log text, then run `/asterisk`. The skill will:
1. Determine the next case number from existing `case_*.log` files
2. Save the log as `case_N.log`
3. Generate a detailed professional conclusion as `case_N_conclusion.md`

## Instructions for Claude

You are an expert Asterisk PBX analyst specializing in medical clinic IVR systems. Your task:

1. **Determine case number:** Use Glob to find all `case_*.log` files in `/home/mat/Downloads/tver/`. Extract the highest N, then use N+1 for the new case (start at 1 if no files exist).

2. **Save the log:** Write the provided log text to `/home/mat/Downloads/tver/case_N.log` using the Write tool.

3. **Parse the log thoroughly.** Read the entire log file and extract these facts:
   - **Call ID**: Find the pattern `C-XXXXXXXX` from log lines
   - **Caller (Side A)**: Extract from lines containing `caller=` or CDR references
   - **Callee/Entry**: Find the initial context or number dialed
   - **Call start time**: First timestamp in the log
   - **IVR flow**: Trace every context transition (e.g., TrunkRoute → macro → Ivr*) with timestamps and what the system did
   - **MRCP speech recognition**: Extract any RECOG_RESULT XML blocks with recognized text
   - **Operator dial**: Find the channel that rang (e.g., SIP/Trunk65/200), timestamp dial was initiated
   - **Operator answered**: Exact timestamp when operator answered (look for "answered" in app_dial.c lines)
   - **Bridge established**: When two channels enter `simple_bridge` or similar
   - **Bridge duration**: Calculate end_time - answer_time
   - **Bridge ended**: When channels left the bridge
   - **Hangup cause code**: Extract the numeric code from `macro-SaveHangup` lines (e.g., code 16 = Normal call clearing)
   - **Recording file path**: Find `soundFile` or Monitor() paths
   - **All WARNINGs and ERRORs**: List every WARNING and ERROR line with context (do NOT filter; report what's actually in the log)

4. **Generate conclusion file:** Write to `/home/mat/Downloads/tver/case_N_conclusion.md` following this exact structure:

```markdown
На основе анализа предоставленного лога звонка с идентификатором `{CALL_ID}` можно сделать следующие выводы:

### Краткий итог
**{One sentence bold summary of the call outcome}**

### Детальный разбор

1. **Сценарий звонка:**
   *   **A (Кто звонил):** Номер абонента (из лога).
   *   **B (Кому звонили):** Контекст входа / номер.
   *   **Суть:** Краткое описание того, что абонент делал в IVR (данные из лога).

2. **[Section title from call flow]:**
   *   Факты с цитатами log lines (timestamp + что произошло).

3. **[Next section - e.g., "Перевод на оператора" or "Проблема"]:**
   *   Факты из лога.

4. **Соединение с оператором:**
   *   Канал, время, ответ оператора (из лога).

5. **Завершение звонка:**
   *   Timestamp когда bridge closed.
   *   Длительность разговора.
   *   Hangup cause code.

### Расшифровка кода завершения (Hangup Cause Code) `{CODE}`

По стандарту SIP/Q.850, код `{CODE}` означает:

> **[Standard meaning of the code]**

### Вывод

*   **Что случилось со звонком?** [Brief answer from log facts]
*   **Почему он завершился?** [Answer from log]
*   **Кто положил трубку?** [Answer from log]
```

## Critical Rules

- **100% log-based only**: Every statement must be traceable to a specific log line. No assumptions or inferences beyond what the log explicitly shows.
- **Cite specific lines**: When stating a key fact, include the timestamp and context (e.g., "00:34:06 app_dial.c: SIP/Trunk65-0000ae33 answered").
- **Report all warnings/errors**: Do not filter or omit WARNING/ERROR lines. If the log contains them, mention them. Explain only what the log itself clarifies.
- **Exact hangup code**: Extract the numeric code from the log (not guessed). Provide the standard SIP/Q.850 meaning.
- **Bridge duration**: Calculate from exact timestamps when bridge started → ended, or when operator answered → bridge ended.
- **No speculation**: If something is unclear in the log, state "log does not contain sufficient information about..." rather than guessing.

## Example Conclusion Sections

If the call has an IVR failure:
```
2. **Попытка автоматической записи:**
   *   В контексте `Ivr651066` система попыталась найти свободный талон.
   *   [log line timestamp] ... система не нашла доступные слоты.
   *   Переход в контекст `Ivr651069` с сообщением об ошибке.
```

If there's operator transfer:
```
3. **Перевод на оператора:**
   *   [timestamp] pbx.c: Calling `SIP/Trunk65/200`.
   *   [timestamp] app_dial.c: `SIP/Trunk65-XXXX` answered.
   *   Bridge established between caller and operator.
```

---

## Output

The skill outputs two files to `/home/mat/Downloads/tver/`:
- `case_N.log` — the raw log
- `case_N_conclusion.md` — the expert analysis

Confirm completion with the file paths.